import React, { Component } from 'react'
import PubSub from "pubsub-js";
// import axios from "axios";

export default class Search extends Component {

  searchInfo = async ()=>{
    //1.获取表单输入(ref现用现取-非受控组件)
    //连续解构赋值+重命名[语法糖]
    const {input:{value:keyword}} = this 

    // 发起请求前通知List组件更新状态
    PubSub.publish('atguigu',{isFirst:false,isLoading:true})

    //使用axios发送网络请求
/*  
    axios.get(`/api/search/users2?q=${keyword}`).then(
      (response)=>{PubSub.publish('atguigu',{isLoading:false,userList:response.data.items,err:''})},
      (error)=>{PubSub.publish('atguigu',{isLoading:false,err:error.message})}
    ) 
*/

    //使用fetch发送网络请求(关注分离)----未优化
/*     
    fetch(`/api/search/users?q=${keyword}`).then(
      response=>{
        console.log('联系服务器成功了',response);
        return response.json()
      },
      error=>{
        console.log('联系服务器失败了',error);
        return new Promise(()=>{})
      }
    ).then (
      response=>{ console.log('获取数据成功了',response);},
      error=>{ console.log('获取数据失败了',error);}
    ) 
*/

    //使用fetch发送网络请求(关注分离)----优化
/*     
    fetch(`/api/search/users2?q=${keyword}`).then(
      response=>{
        console.log('联系服务器成功了',response);
        return response.json()
      }
    ).then (
      response => { console.log('获取数据成功了',response);},
    ).catch(
      error => {console.log('请求出错',error);}
    )
*/

    //使用fetch发送网络请求(关注分离)----最终版
    try {
      const response = await fetch(`/api/search/users2?q=${keyword}`)
      console.log('联系服务器成功');
      const data = await response.json()
      console.log('获取服务器数据成功',data);
      PubSub.publish('atguigu',{isLoading:false,userList:data.items,err:''})
    } catch (error) {
      console.log('请求出错',error);
      PubSub.publish('atguigu',{isLoading:false,err:error.message})
    }
  }
  
  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">搜索Github用户</h3>
        <div>
          <input ref={(c)=>{this.input=c}} type="text" placeholder="输入您搜索的名称"/>&nbsp;
          <button onClick={this.searchInfo}>搜索</button>
        </div>
      </section>
    )
  }
}
